package com.gulimall.ware.listener;

import com.common.to.mq.OrderTo;
import com.common.to.mq.StockLockedTo;
import com.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "stock.release.stock.queue")
@Service
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;


    /**
     * 订单关闭，准备解锁库存
     *
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleOrderLockedRelease(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到过期的订单信息，准备解锁库存" + to.getOrderSn());
        try {
            wareSkuService.unlockStock(to);
            //解锁库存
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            //有异常拒签
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }



    }


    /**
     * 库存自动解锁
     *
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("库存到一定时间自动解锁" + to.getId());
        try {
            wareSkuService.unlockStock(to);
            //解锁库存
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            //有异常拒签
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }



    }











}
